<template>
  <div class="cart">
    <!-- 头部 -->
    <div class="header">
      <span>购物车</span>
      <span @click='editor'>
        <span v-if="editorFlag">编辑</span>
        <span v-else>完成</span>
      </span>
      <!-- <span @click='editorFinish'>完成</span> -->
    </div>
    <!-- 头部结束 -->

    <!-- 购物车内容 -->
     <div class="cart_list">
          <checkbox-group>
            <div class="slide" @touchstart="touchS" @touchmove="touchM($event,index)"  v-for="(item,index) of valueData" :key="index">
            
            <div class="contents_wrapper"  :data-type="item.type">
                <div class="cart_list_item">
                    <div class="checked_wrapper" @click.stop="seletItem(index,item.id)">
                        <checkbox  :value="index" :checked="item.checked"/>
                        <div class="checked_layer"></div>
                    </div>
                    <img :src="item.goods_info.thumb_Url" class="cart_list_item_pic" mode="aspectFill" @click.stop="toGoodsDetail(item.goods_id)">
                    <div class="cart_list_item_right" @click.stop="toGoodsDetail(item.goods_id)">
                        <div class="cart_list_item_name">{{item.goods_info.name}}</div>
                        <div class="cart_list_item_desc" v-show='item.goods_info.goods_spu_info'>规格: {{item.goods_info.goods_spu_info.spu_name}}</div>
                        <div class='count'>
                                <div>￥{{item.goods_info.goods_spu_info.price}}</div>
                            <div class="count_btn">
                                <div  :class="{decrease:true,decrease_least:item.num==flag}" @click.stop="decrease(item)">-</div>
                                <div class="input_num">
                                  <div class="input_num_layer"></div>
                                  <input type="number" :value='item.num' readonly>
                                  </div>
                                <div class="increase" @click.stop="increase(item)">+</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="delete" @click="delt([item.id])">删除</div>
            </div>
        </checkbox-group>
    </div> 
    <!-- 购物车内容结束 -->
    <div class="cart_empty" v-if="valueData.length==0">
      <img src="../../../static/images/tabBar/caret.png" alt="">
      <div>购物车居然没有东西？快去扫货</div>
    </div>
    <!-- 结算栏 -->
    <footer>
      <div class="footer_left">
        <checkbox @click="selectAll" :checked="checkedAll"/>
        <label>全选</label>
      </div>
      <div class="footer_right">
        <div class="footer_right_price" v-if="editorFlag&&selectIdArr.length>0">合计：￥{{money}}</div>
        <div  :class="{footer_right_pay:true,hasItem:selectIdArr.length!=0}">
          <span v-if="editorFlag" @click="toOrder" >去结算</span>
          <span v-else @click="delt(selectIdArr)">删除</span>
          </div>
      </div>
    </footer>
    <!-- 结算栏结束 -->
  </div>
</template>

<script>

import count from '@/components/count'
export default {
  data() {
    return {
      editorFlag:true,//编辑为true，完成为false
      valueData:[],
      selectIdArr:[],//选中状态的id数组
      slideIndex: [],
      checkedAll:false,
      money:'',//总金额
      clientX1:'',//滑动开始位置
      clientX2:'',
      // del:0,//内容初始的right距离
      btnWidth:80,//删除按钮宽度
      flag:1,
      page:0
    }
  },
  watch:{
      valueData:{
          handler:function(nval){
            console.log(nval,'11111')
              this.money=0
              for(let p of nval){
                  if(p.checked==1){
                    this.money+=parseFloat(p.amount_money)
                  }   
              }
              this.money = this.money.toFixed(2);
          },
          deep:true   
      }
  },
  components:{
    count
  },
  methods: {
    toGoodsDetail(id){
      wx.navigateTo({url:'/pages/goodsDetail/main?id='+id})
    },
    async decrease(item){  //计数器的减
        console.log(item)
            let userToken=wx.getStorageSync('userToken')
            const id=item.goods_id;
            const good_spu_id=item.goods_spu_id
            if(parseInt(item.num)>1){
            let res=await this.$request.postData('/goods/addShopCart',{
              goods_id:id,
              num:-1,
              user_token:userToken,
              goods_spu_id:good_spu_id
            })
            if(res.data.level=='success'){
                this.getCartList()
                }
            }
        },
    async increase(item){//计数器的加
      console.log(item)
        let userToken=wx.getStorageSync('userToken')
        const id=item.goods_id;
        const good_spu_id=item.goods_spu_id
        let res=await this.$request.postData('/goods/addShopCart',{
          goods_id:id,
          num:1,
          goods_spu_id:good_spu_id,
          user_token:userToken,
        });
      if(res.data.level=='success'){
        this.getCartList()
      }
    },
    touchS(e){
        // console.log(e)
        this.clientX1=e.clientX
    },
    touchM(e,index){
        this.clientX2=e.clientX
        let disX=this.clientX1-this.clientX2
        if (disX == 0 || disX < 0) {//如果移动距离小于等于0，说明向右滑动，文本层位置不变
            // this.del = 0;
            this.$set(this.valueData[index],'type',0)
        }
        if (disX >= this.btnWidth) {
            //控制手指移动距离最大值为删除按钮的宽度
            // this.del =this.btnWidth;
            this.$set(this.valueData[index],'type',1)
        }
        
    },
    async delt(id){//删除选中的购物车商品
        let userToken=wx.getStorageSync('userToken')
        let res=await this.$request.postData('/goods/deleteShopCart',{shop_cart_ids:id,user_token:userToken})
        if(res.data.level=="success"){
            this.getCartList()
        }
        
    },
    checkboxChange(e) {//获取checkobx选中的value数组
        // console.log('checkbox发生change事件，携带value值为：', e.mp.detail)
        this.slideIndex=e.mp.detail.value;

    },
    seletItem(index,id){//选中商品
    console.log(this.valueData[index],'选中项')
        if(this.valueData[index].checked==0){
            this.$set(this.valueData[index],'checked',1)
            if(!this.selectIdArr.includes(id)){
                this.selectIdArr.push(id)
            }
        }else{
            this.$set(this.valueData[index],'checked',0);
            let arr=this.selectIdArr
            let arr2=[]
            arr.forEach((val)=>{
                if(val!=id){
                    arr2.push(val)
                }
            })
            this.selectIdArr=arr2

        }
        // console.log(this.money)
    },
    editor(){//显示编辑，完成
      let flag=this.editorFlag;
      this.editorFlag=!flag;
    },
    async getCartList(type=''){
        wx.showLoading()
        if(type!='more'){//type为more，是上拉加载更多
            this.page=0
        }
      let userToken=wx.getStorageSync('userToken')
      let res=await this.$request.getData('/goods/getShopCart',{user_token:userToken,page:this.page,limit:10})
     if(res.data.level=='success' && this.selectIdArr.length==0){
       res.data.data.map((item)=>{
            item.type=0//1为右划状态
            item.checked=0;//1为选项选中状态
        })
        wx.hideLoading()
     }else if(res.data.level=='success' && this.selectIdArr.length!=0){
         res.data.data.map((item)=>{
             item.type=0//1为右划状态
             if(this.selectIdArr.includes(item.id)){
                item.checked=1;//1为选项选中状态
             }else{
                 item.checked=0;//1为选项选中状态
             }  
        })
        wx.hideLoading()
     }
     if(type=='more'){
       if (res.data.data.length == 0){
         this.page--;
       } else {
         res.data.data.forEach((val)=>{
           this.valueData.push(val)
         })
       }
     }else{
         this.valueData=res.data.data
     }
     

    //   this.valueData=res.data.data
  },
    async selectAll(){//全选
        let flag=this.checkedAll;
        let arr=this.valueData;
        this.selectIdArr
        if(flag==false){
          this.valueData.map((item)=>{
              item.type=0//1为右划状态
              item.checked=1;//1为选项选中状态
              this.selectIdArr.push(item.id)
          })
          
        }else{
          this.valueData.map((item)=>{
              item.type=0//1为右划状态
              item.checked=0;//1为选项选中状态
              this.selectIdArr=[]
          })
        }
        this.checkedAll=!flag
      },
    async toOrder(){
      if(this.selectIdArr.length==0){
          return
        }
        wx.showLoading()
        let userToken=wx.getStorageSync('userToken')
        let res=await this.$request.postData('/order/submitOrder',{
          type:'shop_cart',
          goods_id:this.selectIdArr,
          num:'',
          goods_spu_id:''
          })
        // let res=await this.$request.postData('/order/buildOrder',{type:'shop_cart',goods_id:this.selectIdArr,user_token:userToken})
        if(res.data.level=="success"){
            wx.hideLoading()
            this.$store.dispatch('setOrder',res.data.data)
            wx.navigateTo({url:`/pages/orderConfirm/main?type=cart`})

        }  
    }
  },
  onShow(){
      this.getCartList()
      this.selectIdArr=[]
      this.$store.dispatch('setCoupon','')//用来清空优惠券，只能这里清空
      this.checkedAll=false//复位全选按钮
    },
 onReachBottom(){
    this.page++;
    this.getCartList('more')
  },
    
  
}
</script>

<style>
/* 小程序checkbox的自定义样式，且不能用scoped */
 checkbox .wx-checkbox-input{
    border-radius: 50%;
    height: 20px;
    width: 20px;
    margin-top: -4px;
    border: 1px solid #eee;
}
checkbox .wx-checkbox-input.wx-checkbox-input-checked::before {
  height: 20px;
  width: 20px;
  line-height: 20px;
  text-align: center;
  font-size: 20px;
  padding: 5px;
  color: #fff;
  border-radius: 50%;
  background-color: red;
  border:1px solid #eee
}
</style>
<style scoped>
.cart{
  width:100%;
    min-height: 100vh;
  overflow-x:hidden;
  background:#eee;
}
  .header{
    width:100%;
    height: 40px;
    background:#eee;
    display:flex;
    justify-content: space-between;
    align-items:center;
  }
  .header>span:nth-child(1){
    margin-left:10px;
  }
  .header>span:nth-child(2){
    margin-right:10px;
  }

  /* 商品列 */
  .cart_list{
    width:100%;
    padding-bottom:50px;
  }
  
  .checked_wrapper{
      position: relative;
      width:40px;
      height: 100%;
  }
  .checked_wrapper>checkbox{
      position:absolute;
      top:50%;
      left:50%;
      transform:translate(-50%)
  }
    .checked_wrapper>.checked_layer{
        position:absolute;
        z-index:999;
        width:100%;
        height:100%;
    }

  /* 结算栏 */
  footer{
    background:#fff;
    position:fixed;
    z-index:101;
    bottom:0;
    height:40px;
    width:100%;
    display:flex;
    align-items:center;
    justify-content:space-between;
  }
  .footer_left{
    margin-left:10px;
  }
  .footer_right{
    display:flex;
    align-items:center
  }
  .footer_right_price{
    color:red;
    margin-right:10px;
  }
  .footer_right_pay{
    background:gray;
    text-align:center;
    color:#fff;
    height: 100%;
    line-height:40px;
    width:80px;
  }
  .hasItem{
      background:red;
  }

  .slide{
        width: 100%;
        position: relative;
        height: 120px;
    }
    .contents_wrapper[data-type="0"]{
        right:0
    }
    .contents_wrapper[data-type="1"]{
        right:80px;
    }
    .contents_wrapper{
        width: 100%;
        height: 100%;
        position: absolute;
        transition: right 0.3s ease-in-out;
        z-index: 99;
        background: #fff
    }
    .contents{
        width: 100%;
    }
    .delete{
        color:#fff;
        height: 100%;
        text-align: center;
        width:80px;
        background: red;
        line-height: 120px;
        position: absolute;
        right:0;
    }
    .cart_list_item{
    width:100%;
    height: 100%;
    display:flex;
    flex-wrap:wrap;
    margin:0 0 0 10px;
    align-items:center;
  }
  .cart_list_item_pic{
    width:80px;
    height: 100px;
    margin-left:10px;
  }
  .cart_list_item_right{
    margin-left:10px;
    width:60%;
    height: 100%;
  }
  .cart_list_item_name{
    width:100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin:10px 0;
  }
  .cart_list_item_desc{
    margin-bottom:10px;
    width:100%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }



  .count{
        width:100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .count_btn{
        margin-right:40px;
        display: flex;
        width:100px;
        height: 25px;
        line-height: 25px;
        text-align: center;
    }
    .decrease,.increase{
        border: 1px solid #eee;
        width:30px;
        height: 100%;
    }
    .decrease{
        border-radius: 5px 0 0 5px;
    }
    .increase{
        border-radius: 0 5px 5px 0;
    }
    .input_num{
      position: relative;
      flex:1;
    }
    .input_num_layer{
      position: absolute;
      width:100%;
      height:100%;
      z-index:3;
    }
    .count_btn input{

        width:100%;
        border-top:1px solid #eee;
        border-bottom:1px solid #eee;
        height:100%;
        min-height: 0 !important;
    }
    .decrease_least{
        background:#eee;
    }

    .cart_empty{
      width:100%;
      position:absolute;
      top:80px;
      margin:0 auto;
      display:flex;
      flex-wrap:wrap;
      justify-content:center;
      align-items:center
    }
    .cart_empty img{
      width:40px;
      height: 40px;
    }
    .cart_empty div{
      width:100%;
      text-align:center;
      font-size:18px;
      margin-top:10px;
    }
</style>
